package com.fudan.sys.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fudan.framework.base.BaseDao;
import com.fudan.framework.base.DaoService;
import com.fudan.sys.dao.RoleDao;
import com.fudan.sys.entity.Role;

@Service
public class RoleService extends DaoService<Role>{

	@Autowired
	private RoleDao roleDao;
	
	@Transactional
	public void addRoleWithPermission(Role role,String[] permissionId) {
		roleDao.save(role);
		if(permissionId != null) {
			for (String permission : permissionId) {
				roleDao.insertPermission(role.getId(), permission);
			}			
		}
	}
	@Override
	public Boolean delete(String id) {
		if("1".equals(id)) {
			throw new RuntimeException("dont delete root user");
		}
		roleDao.deleteById(Integer.parseInt(id));
		return super.delete(id);
	}
	@Transactional
	public void updateRoleWithPermission(Role role,String[] permissionId) {
		update(role);
		roleDao.deleteById(role.getId());
		if(permissionId != null) {
			for (String permission : permissionId) {
				roleDao.insertPermission(role.getId(), permission);
			}			
		}
	}
	
	public List<Integer> findPermissions(Integer roleId) {
		return roleDao.findPermission(roleId);
	}

	@Override
	protected BaseDao<Role> injectDao() {
		return roleDao;
	}
}
